import {
  REDIS_HOST,
  REDIS_PORT,
  CLIENT_ID,
  REDIS_PASSWORD,
} from "config/config";
const Redis = require("ioredis");
const JWT = require("jsonwebtoken");

// 配置redis
export const redis = new Redis({
  host: REDIS_HOST,
  port: REDIS_PORT,
  password: REDIS_PASSWORD,
  // defaultExpiry: 10,
});
redis.on("ready", () => {
  console.log("Redis链接成功");
});
redis.on("error", (err: any) => {
  if (err) {
    console.log("Redis链接错误：" + err);
    redis.quit(); // 链接失败退出链接
  }
});

// 配置redis字段
export function setRedis(key: string, value: any, time?: any) {
  redis.set(key, value);
  redis.expire(key, time ?? 60 * 60 * 12); // 默认12小时
}

// 拿到redis某个字段
export function getRedis(key: string) {
  return new Promise((resolve, reject) => {
    redis.get(key, (err: any, data: any) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
}

// 生成token
export function createToken(userInfo: any) {
  return JWT.sign({ oauth2key: userInfo.key, appid: CLIENT_ID }, "token", {
    expiresIn: "1day",
  });
}
